package logic

import (
    "bytes"
    "context"
    "encoding/json"
    "fmt"
    "mime/multipart"
    "net/http"
    "strconv"

    "goNutpi/internal/svc"
    "goNutpi/internal/types"

    "github.com/zeromicro/go-zero/core/logx"
    "github.com/zeromicro/go-zero/rest/httpc"
)

type TopicCtrlLogic struct {
    logx.Logger
    ctx     context.Context
    svcCtx  *svc.ServiceContext
    baseURL string
}

func NewTopicCtrlLogic(ctx context.Context, svcCtx *svc.ServiceContext) *TopicCtrlLogic {
    return &TopicCtrlLogic{
        Logger:  logx.WithContext(ctx),
        ctx:     ctx,
        svcCtx:  svcCtx,
        baseURL: "https://api.nutpi.net",
    }
}

func (l *TopicCtrlLogic) TopicCtrl(req *types.CtrlTopicReq) (resp *types.CtrlTopicResp, err error) {
    resp = &types.CtrlTopicResp{}

    itemId, err := strconv.Atoi(req.ItemId)
    if err != nil {
        resp.Code = 400
        resp.Msg = "无效的 itemId"
        return resp, nil
    }

    module, err := strconv.Atoi(req.Module)
    if req.Module != "" && err != nil {
        resp.Code = 400
        resp.Msg = "无效的 module"
        return resp, nil
    }

    switch req.Action {
    case "like":
        err = l.addLike(itemId, module, req.Auth)
    case "favorite":
        err = l.addFavorite(itemId, req.Auth)
    case "unlike":
        err = l.removeLike(itemId, module, req.Auth)
    case "unfavorite":
        err = l.removeFavorite(itemId, req.Auth)
    default:
        resp.Code = 400
        resp.Msg = "不支持的操作类型"
        return resp, nil
    }

    if err != nil {
        resp.Code = 500
        resp.Msg = err.Error()
        return resp, err
    }

    resp.Code = 0
    resp.Msg = "操作成功"
    resp.Data = fmt.Sprintf("执行了 %s 操作，itemId: %d, module: %s", req.Action, itemId, req.Module)
    return resp, nil
}

// 添加点赞方法
func (l *TopicCtrlLogic) addLike(itemId, module int, auth string) error {
    url := fmt.Sprintf("%s/user/control/like/add", l.baseURL)
    formData := map[string]string{
        "itemId": strconv.Itoa(itemId),
        "module": strconv.Itoa(module),
    }

    return l.sendPostRequest(url, formData, auth)
}

// 添加收藏方法
func (l *TopicCtrlLogic) addFavorite(topicId int, auth string) error {
    url := fmt.Sprintf("%s/user/control/favorite/add", l.baseURL)
    formData := map[string]string{
        "topicId": strconv.Itoa(topicId),
    }

    return l.sendPostRequest(url, formData, auth)
}

// 移除点赞方法
func (l *TopicCtrlLogic) removeLike(itemId, module int, auth string) error {
    url := fmt.Sprintf("%s/user/control/deleteLike?itemId=%d&module=%d", l.baseURL, itemId, module)
    return l.sendDeleteRequest(url, auth)
}

// 移除收藏方法
func (l *TopicCtrlLogic) removeFavorite(topicId int, auth string) error {
    url := fmt.Sprintf("%s/user/control/deleteFavorite?topicId=%d", l.baseURL, topicId)
    return l.sendDeleteRequest(url, auth)
}

// 发送 POST 请求
func (l *TopicCtrlLogic) sendPostRequest(url string, formData map[string]string, auth string) error {
    body := &bytes.Buffer{}
    writer := multipart.NewWriter(body)

    // 添加字段
    for key, value := range formData {
        if err := writer.WriteField(key, value); err != nil {
            return err
        }
    }

    err := writer.Close()
    if err != nil {
        return err
    }

    req, err := http.NewRequest("POST", url, body)
    if err != nil {
        return err
    }
    req.Header.Set("Authorization", auth)
    req.Header.Set("X-Requested-With", "XMLHttpRequest")
    req.Header.Set("Content-Type", writer.FormDataContentType())

    resp, err := httpc.DoRequest(req)
    if err != nil {
        return err
    }
    defer resp.Body.Close()

    if resp.StatusCode != http.StatusOK {
        return l.parseHTTPError(resp)
    }

    return nil
}

// 发送 DELETE 请求
func (l *TopicCtrlLogic) sendDeleteRequest(url string, auth string) error {
    req, err := http.NewRequest("DELETE", url, nil)
    if err != nil {
        return err
    }
    req.Header.Set("Authorization", auth)
    req.Header.Set("X-Requested-With", "XMLHttpRequest")

    resp, err := httpc.DoRequest(req)
    if err != nil {
        return err
    }
    defer resp.Body.Close()

    if resp.StatusCode != http.StatusOK {
        return l.parseHTTPError(resp)
    }

    return nil
}

// 解析HTTP错误响应
func (l *TopicCtrlLogic) parseHTTPError(resp *http.Response) error {
    var errorResp struct {
        Code int    `json:"code"`
        Msg  string `json:"msg"`
    }
    err := json.NewDecoder(resp.Body).Decode(&errorResp)
    if err != nil {
        return fmt.Errorf("HTTP请求失败，状态码: %d", resp.StatusCode)
    }

    return fmt.Errorf("HTTP请求失败，状态码: %d, 错误信息: %s", resp.StatusCode, errorResp.Msg)
}
